package mi.payment.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.RemoteException;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.sunmi.pay.hardware.aidl.system.BasicOpt;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import mi.payment.MyApplication;
import mi.payment.R;
import mi.payment.db.dao.PayDetail;
import sunmi.sunmiui.utils.LogUtil;

/**
 * @author tomcat on 2017/3/15.
 */

public class UIUtils {

    private final static String TAG = "UIUtils";

    private static final int SYSTEM_UI_FLAG_SUN_MI_SEC = 0x00000008;

    /**
     * 屏幕独占 禁用底部导航栏和SystemUI下拉框
     */
    private static void setSecStatusBar(View view) {
        int systemUiVisibility = view.getSystemUiVisibility();
        systemUiVisibility |= SYSTEM_UI_FLAG_SUN_MI_SEC;
        view.setSystemUiVisibility(systemUiVisibility);
    }

    private static void banPowerKey(Window window) {
        if (window != null) {
            window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND);//禁用PowerKey
        }
    }

    private static void banVolumeKey(Dialog dialog) {
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {

            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                String tag = "onKeyDown";
                if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
                    LogUtil.e(tag, "KEYCODE_VOLUME_DOWN");
                    return true;
                } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
                    LogUtil.e(tag, "KEYCODE_VOLUME_UP");
                    return true;
                }
                return false;
            }

        });
    }

    /**
     * 屏幕独占
     */
    public static void screenMonopoly(int mode) {
        LogUtil.e(TAG, (mode == 1 || mode == 2) ? "set screenMonopoly" : "cancel screenMonopoly ");
        try {
            BasicOpt basicOpt = MyApplication.getInstance().basicOptBinder;
            if (basicOpt != null) {
                basicOpt.setScreenMode(mode);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        // banPowerKey(window);
        // setSecStatusBar(window.getDecorView());
        // 应用运行时，保持屏幕高亮，不锁屏
        // window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    /**
     * 屏幕独占金融模式
     */
    public static void screenFinancialModel() {
        LogUtil.e(TAG, "set screenFinancialModel");
        int uid = MyApplication.getInstance().getApplicationInfo().uid;
        try {
            MyApplication.getInstance().basicOptBinder.setScreenMode(uid);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置当前界面亮度
     * 需要注意其中的context的类型是Activity，不能是Context。
     * 这种方式的特点，是**只在当前设置的界面生效**，离开此界面后，屏幕亮度受亮度自动调节的开关控制。
     * 换句话说，用这种方式设置当前界面的亮度时，会使亮度自动调节失效。
     * 只有离开此界面，亮度自动调节继续生效。这种方式适用某些特殊的，需要高亮显示界面。
     */
    public static void setLight(Activity context, int brightness) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.screenBrightness = Float.valueOf(brightness) * (1f / 255f);
        context.getWindow().setAttributes(lp);
    }


    // string相关
    public static String getQRPaymentTitle(PayDetail payDetail) {
        StringBuilder sb = new StringBuilder();
        if (payDetail.getTransPlatform() == 1) { // 支付宝
            sb.append(getString(R.string.alipay));
        } else if (payDetail.getTransPlatform() == 2) { // 微信
            sb.append(getString(R.string.wechat));
        } else if (payDetail.getTransPlatform() == 4) { // 银联
            sb.append(getString(R.string.union));
        } else if (payDetail.getTransPlatform() == 5) { // 小米
            sb.append(getString(R.string.mipay));
        }
        sb.append(getString(R.string.payment));
        return sb.toString();
    }

    public static String getPaymentType(PayDetail payDetail) {
        String builder = "";
        if (payDetail.getTransPlatform() == 1) {
            // 支付宝
            builder += getString(R.string.platform_ali);
        } else if (payDetail.getTransPlatform() == 2) {
            // 微信
            builder += getString(R.string.platform_wx);
        } else if (payDetail.getTransPlatform() == 4) {
            builder += getString(R.string.platform_union);
        } else {
            builder += "";
        }
        switch (payDetail.transactionType) {
            case 1: //消费
                if (payDetail.getQrCodeScanModel() == 1) {
                    // 主扫
                    builder += getString(R.string.platform_scan_merchant);
                } else if (payDetail.getQrCodeScanModel() == 2) {
                    // 被扫
                    builder += getString(R.string.platform_scan_customer);
                }
                break;
            case 2: // 撤销
                builder += getString(R.string.consume_revoke);
                break;
            case 3: // 退款
                builder += getString(R.string.refund);
                break;
            default:
                builder += "";
                break;
        }
        return builder;
    }

    public static String getQRPaymentTypeSuffix(int transType) {
        StringBuilder sb = new StringBuilder();
        switch (transType) {
            case 1:
                // 主扫
                sb.append(getString(R.string.scan_code));
                break;
            case 2:
                // 被扫
                sb.append(getString(R.string.platform_code));
                break;
            default:
                sb.append("");
                break;
        }
        sb.append(getString(R.string.payment));
        return sb.toString();
    }

    /**
     * 11:支付宝 12:微信支付 13:小米钱包 21:银联二维码借记  22银联二维码贷记
     *
     * @param name
     * @return
     */
    public static int getTransPlatformByName(String name) {
        // 支付方式  1：支付宝；2:微信;4:银联钱包; 5:小米钱包
        if (name.equals("11")) {
            return 1;
        } else if (name.equals("12")) {
            return 2;
        } else if (name.equals("21") || name.equals("22")) {
            return 4;
        } else if (name.equals("13")) {
            return 5;
        }
        return 1;
    }

    public static String getQRPaymentTypePrefix(int platform, int transType) {
        StringBuilder paymentTypeSB = new StringBuilder();
        if (platform == 1) { // 支付宝
            paymentTypeSB.append(getString(R.string.alipay));
        } else if (platform == 2) { // 微信
            paymentTypeSB.append(getString(R.string.wechat));
        } else if (platform == 4) {
            paymentTypeSB.append(getString(R.string.union));
        } else if (platform == 5) {
            paymentTypeSB.append(getString(R.string.mipay));
        }
        switch (transType) {
            case 1: // 主扫
                paymentTypeSB.append(getString(R.string.scan_code));
                break;
            case 2: // 被扫
                paymentTypeSB.append(getString(R.string.platform_code));
                break;
            default:
                paymentTypeSB.append("");
                break;
        }
        return paymentTypeSB.toString();
    }

    public static String getString(int id) {
        return MyApplication.getInstance().getString(id);
    }

    public static String getString(int id, String msg) {
        return MyApplication.getInstance().getString(id, msg);
    }

    /*增加根据类型获取交易名称 by Ricardo start*/

    /**
     * 获取交易名称
     *
     * @param type {@link PayDetail#transactionType}
     */
    public static String getTransactionTypeName(int type) {
        /*1:消费 2：消费撤销；3：退货  4.预授权 5.预授权撤销 6.预授权完成 7.预授权完成撤销 8.结算 9.签到 10.签退 11.交易查询*/
        switch (type) {
            case 1:
                return getString(R.string.consume_im_title);
            case 2:
                return getString(R.string.cancellation_title);
            case 3:
                return getString(R.string.return_title);
            case 4:
                return getString(R.string.traditional_transaction_pre_auth);
            case 5:
                return getString(R.string.traditional_transaction_pre_auth_cancel);
            case 6:
                return getString(R.string.pre_auth_complete);
            case 7:
                return getString(R.string.pre_authorization_complete_revoke);
            case 8:
                return getString(R.string.settlement);
            case 9:
                return getString(R.string.sign_title);
            case 10:
                return getString(R.string.sign_out_now);
            case 11:
                return getString(R.string.transaction_query);
        }
        return "";
    }
    /*增加根据类型获取交易名称 by Ricardo end*/

    /**
     * 校验卡片有效期
     *
     * @param EXPDate 长度只能是4位且: 前面两位数字必须是00-99，后面两位必须是01-12
     * @return
     */
    public static boolean checkEXPDate(String EXPDate) {
        return TextUtils.isEmpty(EXPDate) || YearMonthMatcher.reset(EXPDate).matches();
    }

    private static final Matcher YearMonthMatcher =
            Pattern.compile("(?:\\d\\d)(?:0[1-9]|1[0-2])").matcher("");

}